package com.wenzhoujie.adapter;

import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.facebook.controller.utils.ToastUtil;
import com.wenzhoujie.ShopCartActivity;
import com.wenzhoujie.app.App;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.adapter.SDBaseAdapter;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.wenzhoujie.model.CartGoodsModel;
import com.wenzhoujie.model.GoodsAttrsModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.ShopGoodsModel;
import com.wenzhoujie.model.act.GoodsdescActModel;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewHolder;

public class ShopCartAdaptertest extends SDBaseAdapter<ShopGoodsModel> {
	LocalUserModel user = null;

	public ShopCartAdaptertest(List<ShopGoodsModel> listModel, Activity activity) {
		super(listModel, activity);
		user = App.getApplication().getmLocalUser();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// if (convertView == null)
		// {
		convertView = mInflater.inflate(R.layout.item_shop_cart, null);
		// }

		TextView tvAddNumber = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_add_number);
		TextView tvMinusNumber = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_minus_number);
		EditText etNumber = ViewHolder.get(convertView,
				R.id.item_shop_cart_et_edit_number);
		TextView ivDeleteItem = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_delete);
		ImageView ivGoodsImage = ViewHolder.get(convertView,
				R.id.item_shop_cart_iv_goods_image);
		LinearLayout llAttrs = ViewHolder.get(convertView,
				R.id.item_shop_cart_ll_goods_attr);
		TextView tvAttrATitle = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_attr_a_title);
		TextView tvAttrAValue = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_attr_a_value);
		TextView tvAttrBTitle = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_attr_b_title);
		TextView tvAttrBValue = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_attr_b_value);
		TextView tvGoodsName = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_goods_name);
		TextView tvSinglePrice = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_single_price);
		TextView tvTotalPrice = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_total_price);

		/*---------------------暂时用不倒---------------------*/
		
		tvAttrBTitle.setVisibility(View.GONE);
		tvAttrBValue.setVisibility(View.GONE);
		
		ShopGoodsModel cartModel = getItem(position);
		if (cartModel != null) {
			String attr_str=cartModel.getAttr_str();
			if(attr_str.equals(""))
			{
				tvAttrATitle.setVisibility(View.GONE);
				tvAttrAValue.setVisibility(View.GONE);
			}else{
				tvAttrAValue.setText(attr_str);
			}
			SDViewBinder.setImageView(ivGoodsImage,
					"http://www.52lingou.com/sjmapi/." + cartModel.getIcon()); // 设置商品图片
			SDViewBinder.setTextView(tvGoodsName, cartModel.getName()); // 设置商品名称
			/*
			 * if (SDViewBinder.setViewsVisibility(llAttrs,
			 * cartModel.isHas_attr())) // 有属性 {
			 * SDViewBinder.setTextView(tvAttrATitle, cartModel.getAttr_str());
			 * SDViewBinder.setTextView(tvAttrAValue, cartModel.getAttr());
			 * 
			 * }
			 */

			etNumber.setText(cartModel.getNumber());
			SDViewBinder.setTextView(tvSinglePrice,
					stringTo2double(cartModel.getUnit_price())); // 商品单价
			SDViewBinder.setTextView(tvTotalPrice,
					stringTo2double(cartModel.getTotal_price())); // 小计价格

			ivDeleteItem.setOnClickListener(new ViewClickListener(position,
					convertView, cartModel));// 删除按钮监听

			tvAddNumber.setOnClickListener(new ViewClickListener(position,
					convertView, cartModel)); // 增加按钮

			tvMinusNumber.setOnClickListener(new ViewClickListener(position,
					convertView, cartModel)); // 减少按钮
			/*
			 * etNumber.addTextChangedListener(new
			 * GoodsNumberTextWatcher(position, convertView, cartModel));
			 */

		}

		return convertView;
	}

	class ViewClickListener implements OnClickListener {

		private int nPosition = -1;
		private View nConvertView = null;
		private ShopGoodsModel nCartModel = null;

		public ViewClickListener(int nPosition, View convertView,
				ShopGoodsModel cartModel) {
			super();
			this.nPosition = nPosition;
			this.nConvertView = convertView;
			this.nCartModel = cartModel;
		}

		@Override
		public void onClick(View v) {
			if (nCartModel != null) {
				switch (v.getId()) {
				case R.id.item_shop_cart_tv_delete: // 删除按钮
					deleteShopCart(nCartModel.getId());
					mListModel.remove(nCartModel);
					notifyDataSetChanged();
					break;
				case R.id.item_shop_cart_tv_add_number: // 增加按钮

					int numAdd = Integer
							.parseInt(nCartModel.getNumber().trim());
					if (numAdd > 0) {
						if (numAdd >= 99) {
							SDToast.showToast("已经达到最大购买数量");
						} else {
							updateShopCart(
									nCartModel.getId(),
									nCartModel,
									nConvertView,
									Integer.parseInt(nCartModel.getNumber()) + 1,
									true);
						}
					}
					break;
					// updateViewsData(nCartModel, nConvertView, true);

				case R.id.item_shop_cart_tv_minus_number: // 减少按钮

				/*	int numMinus = nCartModel.minusNumber();
					if (numMinus > 0) {
						if (numMinus == 1) {
							SDToast.showToast("购买数量不能小于1");
						}
						updateViewsData(nCartModel, nConvertView, true);
					}*/
					int numMinus=Integer.parseInt(nCartModel.getNumber());
					if (numMinus > 0) {
						if (numMinus == 1) {
							SDToast.showToast("购买数量不能小于1");
						} else {
							updateShopCart(nCartModel.getId(), nCartModel,
									nConvertView, Integer.parseInt(nCartModel.getNumber())
									- 1, true);
						}
					}

					break;

				default:
					break;
				}
			}

		}
	}

	private void updateViewsData(CartGoodsModel cartModel, View convertView,
			boolean updateEditText) {

		TextView tvTotalPrice = ViewHolder.get(convertView,
				R.id.item_shop_cart_tv_total_price);
		tvTotalPrice.setText(cartModel.getTotal_format_string());
		if (updateEditText) {
			EditText etNumber = ViewHolder.get(convertView,
					R.id.item_shop_cart_et_edit_number);
			etNumber.setText(cartModel.getNum());
		}
	}

	class GoodsNumberTextWatcher implements TextWatcher {
		private int nPosition = -1;
		private View nConvertView = null;
		private CartGoodsModel nCartModel = null;

		public GoodsNumberTextWatcher(int nPosition, View convertView,
				CartGoodsModel nCartModel) {
			super();
			this.nPosition = nPosition;
			this.nConvertView = convertView;
			this.nCartModel = nCartModel;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			if (nCartModel != null) {
				int num = SDTypeParseUtil.getIntFromString(s.toString(), 0);
				int limitNum = SDTypeParseUtil.getIntFromString(
						nCartModel.getLimit_num(), 0);
				if (limitNum > 0) {
					if (num <= 0) {
						num = 1;
						SDToast.showToast("购买数量不能小于1");
						nCartModel.setNum(String.valueOf(num));
						updateViewsData(nCartModel, nConvertView, true);
					} else if (num > limitNum) {
						num = limitNum;
						SDToast.showToast("已经达到最大购买数量");
						nCartModel.setNum(String.valueOf(num));
						updateViewsData(nCartModel, nConvertView, true);
					} else if (num < limitNum) {
						nCartModel.setNum(String.valueOf(num));
						updateViewsData(nCartModel, nConvertView, false);
					} else if (num == limitNum) {
						SDToast.showToast("已经达到最大购买数量");
						nCartModel.setNum(String.valueOf(num));
						updateViewsData(nCartModel, nConvertView, false);
					}
				}
			}
		}

	}

	// 删除购物车
	private void deleteShopCart(String cart_id) {
		RequestModel model = new RequestModel();
		model.put("act", "cart");
		model.put("a", "del");
		model.put("cart_id", cart_id);
		model.put("email", user.getUser_name());
		model.put("pwd", user.getUser_pwd());
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				JSONObject json = JSON.parseObject(responseInfo.result);
				if (json.getString("response_code").equals("true")) {
					ToastUtil.showToast(App.getApplication(), "删除成功");
				} else {
					ToastUtil.showToast(App.getApplication(), "删除失败");
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {

			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	// 更新购物车
	private void updateShopCart(String cart_id, final ShopGoodsModel cartModel,
			final View convertView, final int number, final boolean updateEditText) {
		final EditText etNumber = ViewHolder.get(convertView,
				R.id.item_shop_cart_et_edit_number);
		RequestModel model = new RequestModel();
		model.put("act", "cart");
		model.put("a", "upd");
		model.put("cart_id", cart_id);
		model.put("num", number + "");
		model.put("email", user.getUser_name());
		model.put("pwd", user.getUser_pwd());
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				JSONObject json = JSON.parseObject(responseInfo.result);
				JSONObject json_response_code = JSON.parseObject(json
						.getString("response_code"));
				// Toast.makeText(getActivity(), json+"", 1).show();
				TextView tvTotalPrice = ViewHolder.get(convertView, R.id.item_shop_cart_tv_total_price);
				
				//String total_price = json_response_code.getString("total_price");
				String total_price = "" + number * Double.parseDouble(cartModel.getUnit_price());
				total_price = stringTo2double(total_price);// string结果
				Double total_price_double = Double.parseDouble(total_price); // double结果

				if (total_price_double > 0) {
					cartModel.setTotal_price(total_price);
				}
				tvTotalPrice.setText(cartModel.getTotal_price());
				// tvTotalPrice.setText(cartModel.getTotal_format_string());
				if (updateEditText) {
					cartModel.setNumber(number + "");
					etNumber.setText(Integer.parseInt(cartModel.getNumber())
							+ "");
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {

			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	public String stringTo2double(String num) {
		Double total_price_double = Double.parseDouble(num);
		DecimalFormat df = new DecimalFormat("###.00");
		return df.format(total_price_double);
	}
}
